package com.bobo.controller;

import com.bobo.view.AlgoFrame;
import com.bobo.model.Circle;
import com.bobo.units.AlgoVisUnit;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @Author: bobobo
 * @Date: 2019/9/3 11:34
 * @Version：1.0
 */
public class AlgoVisualizer {
	private static int DELAY = 40;
    //TODO 创建自己的数据
    private Circle[] circles;  //数据
    private AlgoFrame frame;   //视图
    private boolean isAnimated = true;

    public AlgoVisualizer(int sceneWidth,int sceneHeight,int N){
        //TODO 初始化自己的数据
        //初始化数据
        circles = new Circle[N];
        int R = 50;
        for(int i = 0;i < N;i++){
            int x = (int) ((Math.random()*sceneWidth - 2*R) + R);
            int y = (int) ((Math.random()*sceneHeight - 2*R) + R);
            int vx = (int) ((Math.random()*11) - 5);
            int vy = (int) ((Math.random()*11) - 5);
            circles[i] = new Circle(x,y,R,vx,vy);
        }

        //初始化视图
        // 事件队列 创建新线程===事件分发线程
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("随机生成圆",sceneWidth,sceneHeight);
            //TODO 根据情况决定是否添加 键盘鼠标等事件监听器
            frame.addKeyListener(new AlgoKeyListener());
            frame.addMouseListener(new AlgoMouseListener());

            new Thread(() -> {
                run();
            }).start();
        });
    }

    //动画逻辑
    private void run(){
        //TODO 编写自己的动画逻辑
        while (true){
            //绘制数据
            frame.render(circles);
            AlgoVisUnit.pause(DELAY);

            //更新数据
            if (isAnimated)
                for (Circle circle:circles) {
                    circle.move(frame.getCanvasWidth(),0,frame.getCanvasHeight(),0);
                }
        }
    }

    //TODO 根据情况决定是否实现 键盘鼠标等事件监听器类
    private class AlgoKeyListener extends KeyAdapter{
        @Override
        public void keyReleased(KeyEvent event) {
            super.keyReleased(event);
            if (event.getKeyChar() == ' '){
                isAnimated = !isAnimated;
            }
        }
    }

    private class AlgoMouseListener extends MouseAdapter{
        @Override
        public void mousePressed(MouseEvent event) {
            super.mousePressed(event);
            event.translatePoint(0,-(frame.getBounds().height - frame.getCanvasHeight()));
            //System.out.println(event.getPoint());
            for (Circle circle:circles) {
                if (circle.contain(event.getPoint()))
                    circle.isFilled = !circle.isFilled;
            }
        }
    }
}
